import 'dart:io';
import 'package:cloud_medicine/components/above_loading.dart';
import 'package:cloud_medicine/components/close_circle.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/model/shop_list.dart';
import 'package:cloud_medicine/pages/image_show.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ShopEditUpImage extends StatefulWidget {
  final num pagekind; //0为药店编辑  1为药品编辑
  ShopEditUpImage({Key key, this.pagekind}) : super(key: key);

  @override
  _ShopEditUpImageState createState() => _ShopEditUpImageState();
}

class _ShopEditUpImageState extends State<ShopEditUpImage> {
  bool _loading = false;
  List<String> _imageList = []; //选择的图片
  final picker = ImagePicker();
  List<String> _existedImage = []; //原先已经存在的图片
  DateTime lastPopTime; //上次点击时间

  @override
  void initState() {
    super.initState();
    _init();
  }

  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });
    await Future.delayed(Duration(seconds: 2), () {
      if (mounted) {
        setState(() {
          _loading = false;
          _existedImage = [
            'http://m.yihetang-jm.com/skin/picture/abuiabacgaagkjwe0quoqnnzoqmw0au4rau!1000x1000.jpg'
          ];
        });
      }
    });
    return;
  }

  // 生成gridView的网格视图图片
  List<Widget> getWidgetList() {
    List<Widget> filesListShow = [];
    for (int i = 0; i < _existedImage.length; i++) {
      filesListShow.add(getItemContainer(_existedImage[i], i));
    }
    for (int j = 0; j < _imageList.length; j++) {
      filesListShow.add(getFileItemContainer(_imageList[j], j));
    }
    // 增加最后的一个添加图片的图标
    filesListShow.add(GestureDetector(
      onTap: pickImage,
      child: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
            border: Border.all(width: 1, color: Colors.lightBlueAccent)),
        child: Icon(Icons.add, color: Colors.lightBlueAccent),
      ),
    ));
    return filesListShow;
  }

  // 生成每一张图片的样式
  Widget getItemContainer(String file, int index) {
    return GestureDetector(
      child: Container(
        child: Stack(
          children: <Widget>[
            Align(
              child: FadeInImage.assetNetwork(
                placeholder: 'images/loading.gif', // 占位图
                image: file,
              ),
              alignment: Alignment.center,
            ),
            Align(
              child: CloseCircle(index: index, callback: deleteImage),
              alignment: Alignment(0.9, -0.9),
            )
          ],
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ImageShow(
                  url: file,
                  isFile: false,
                )));
      },
    );
  }

  // 生成每一张图片的样式（路径来源于文件）
  Widget getFileItemContainer(String file, int index) {
    return GestureDetector(
      child: Container(
        child: Stack(
          children: <Widget>[
            Align(
              child: Image.network(file),
              alignment: Alignment.center,
            ),
            Align(
              child: CloseCircle(index: index, callback: deleteImage),
              alignment: Alignment(0.9, -0.9),
            )
          ],
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ImageShow(
                  url: file,
                  isFile: true,
                )));
      },
    );
  }

  // 删除图片
  void deleteImage(int index) {
    if (index >= _existedImage.length) {
      //判断是原来已有的还是后来添加的
      setState(() {
        _imageList.removeAt(index - _existedImage.length);
      });
    } else {
      setState(() {
        _existedImage.removeAt(index);
      });
    }
  }

  // 在底部显示图片选取方式
  pickImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 120,
              child: Column(
                children: <Widget>[_item('拍照', true), _item('从相册选择', false)],
              ),
            ));
  }

  // 在底部生成每一项部件
  _item(String title, bool isTakePhoto) {
    return GestureDetector(
      child: ListTile(
        leading: Icon(isTakePhoto ? Icons.camera_alt : Icons.photo_library),
        title: Text(title),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }

  // 拍照或从图库中选取图片
  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    final pickedFile = await picker.getImage(
        source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);
    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading();
        });

    upLoadImage(File(pickedFile.path), (imgurl) {
      setState(() {
        _imageList.add(imgurl);
      });
      Navigator.pop(context);
    });
  }

  // 判断loading并且在loading为false时渲染主要视图
  Widget _childLayout() {
    if (_loading) {
      return loadingWidget(_loading);
    } else {
      return ListView(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(8),
            child: GridView.count(
              physics: new NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              crossAxisSpacing: 10.0,
              mainAxisSpacing: 10.0,
              crossAxisCount: 3,
              childAspectRatio: 1.0,
              children: getWidgetList(),
            ),
          )
        ],
      );
    }
  }

  _entryPostDetaiPage() {
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime) > Duration(seconds: 1)) {
            //两次点击间隔超过1秒则重新计时
            lastPopTime = DateTime.now();
            openAlertDialog(
                context, _entryPostDetaiPage, '确认退出编辑，一旦退出，一切将不予保存');
            return new Future.value(false);
          }
          return new Future.value(true);
        },
        child: Scaffold(
            backgroundColor: Colors.grey[300],
            appBar: AppBar(
              title: Text('上传照片'),
            ),
            body: _childLayout(),
            floatingActionButton: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                _container(),
                Container(
                    width: double.infinity,
                    margin: EdgeInsets.only(left: 30, top: 20),
                    child: RaisedButton(
                        child:
                            Text('上传', style: TextStyle(color: Colors.white)),
                        color: Colors.blue,
                        onPressed: () {
                          if (widget.pagekind == 0) {
                            setState(() {
                              imgUp.add(_imageList[0]);
                            });
                          } else {
                            setState(() {
                              medicineImgUp.addAll(_imageList);
                              print(medicineImgUp);
                            });
                          }
                          Navigator.pop(context);
                        })),
              ],
            )));
  }

  _container() {
    if (widget.pagekind == 0) {
      return Container(
          child: Text(
        '只能上传一张图片~',
        style: TextStyle(color: Colors.grey[400]),
      ));
    } else {
      return Container(
          child: Text(
        '可上传多张图片~',
        style: TextStyle(color: Colors.grey[400]),
      ));
    }
  }
}
